"""
Project Euler Problem 4: https://projecteuler.net/problem=4

Largest palindrome product

A palindromic number reads the same both ways. The largest palindrome made
from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.
"""

# _*_ conding:UTF-8 _*_
'''
@author = Kuperain
@email = kuperain@aliyun.com
@IDE = Thonny Python3.8
@creat_time = 2022/5/4
'''
def isPalindromicNumber(n: int) -> bool:
    '''
    >>> isPalindromicNumber(12321)
    True
    >>> isPalindromicNumber(1221)
    True
    >>> isPalindromicNumber(1234326)
    False
    >>> isPalindromicNumber(1230)
    False
    '''
    if n%10 == 0:
        return False
    nStr = str(n)
    halfLen = len(nStr)//2

    for i in range(halfLen):
        if nStr[i] == nStr[-(i+1)]:
            continue
        else:
            return False
    return True

def solution1(b: int = 3) -> int:
    maxNum = 10**b - 1
    minNum = 10**(b-1)
    
    res = (0, 0, 0)
    for i in range(maxNum,minNum,-1):
        if i%10 == 0:
            continue
        for j in range(maxNum,minNum,-1):
            if j%10 == 0:
                continue
            if isPalindromicNumber(i*j):
                res = (i, j, i*j) if i*j>res[2] else res
    return res

def solution2(b: int = 3) -> int:
    maxNum = 10**b - 1
    minNum = 10**(b-1)  
    res = maxNum**2
    res_min = minNum**2

    while res > res_min:
        if isPalindromicNumber(res):
            factor = maxNum
            factor_min = minNum
            while factor > factor_min:
                if factor % 10 == 0:
                    factor = factor - 1
                    continue
                tmp = divmod(res, factor)
                if tmp[1] == 0 and len(str(tmp[0]))== b:
                    return factor, tmp[0], res
                factor = factor - 1
                
        res = res - 1
        
    return

if __name__ == "__main__":
    import doctest, time
    doctest.testmod(verbose = True)
    
    start = time.time()
    
    print(f"{solution1() = }")
    time1 = time.time()
    print(f'耗时：{time1 - start}s')
    
    print(f"{solution2() = }")
    time2 = time.time()
    print(f'耗时：{time2 - time1}s')
    
    '''
    solution1() = (993, 913, 906609)
    耗时：1.6720037460327148s
    solution2() = (993, 913, 906609)
    耗时：0.26000046730041504s
    '''
    


